﻿using System;
using System.ComponentModel.DataAnnotations;

namespace Products.Databases
{
    [Serializable]
    public class Field : DatabaseObject
    {
        protected Field()
        {
        }

        internal Field(ProductVersion productVersion, Table table)
            : base(productVersion)
        {
            this.Table = table;
        }
        /// <summary>
        /// Gets the Table include this field.
        /// </summary>
        public virtual Table Table { get; private set; }
        /// <summary>
        /// Gets or sets the SqlType
        /// </summary>
        [Required]
        public virtual string SqlType
        {
            get { return CurrentSnapshot.SqlType; }
            set { CurrentSnapshot.SqlType = value; }
        }
        /// <summary>
        /// Gets or sets the Length.
        /// </summary>
        [Required, RegularExpression("\\d+", ErrorMessage = "Please input number.")]
        public virtual int Length
        {
            get { return CurrentSnapshot.Length; }
            set { CurrentSnapshot.Length = value; }
        }   
        
        private FieldSnapshot CurrentSnapshot
        {
            get { return (FieldSnapshot)base.CurrentSnapshot; }
        }

        protected override ISnapShot CreateNewStateChange(ProductVersion productVersion, ActionType actionType)
        {
            return new FieldSnapshot(productVersion, actionType, this);
        }

        protected override void FillDeleteVersion(ISnapShot deletedSnap, ISnapShot lastSnapshot)
        {
            base.FillDeleteVersion(deletedSnap, lastSnapshot);
            var fieldSnap = (FieldSnapshot)deletedSnap;
            var lastFieldSnap = (FieldSnapshot)lastSnapshot;
            fieldSnap.SqlType = lastFieldSnap.SqlType;
            fieldSnap.Length = lastFieldSnap.Length;
        }
    }
}